package com.wdb007.venus.svc.biz.manager;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.biz.utils.WsStrUtils;

@Component("wsClientSenderApp")
public class WSClientSenderApp implements InitializingBean{

	private Logger logger = LoggerFactory.getLogger(WSClientSenderApp.class);
	
	private long userid;
	
	private String grid_code ;
	
	private String serverName = "serverName" ;
	
	private String action ;
	
	private String location = ""; 
	@Resource(name="sslClientApp")
    private SSLClientApp sslClient;
	
	private URI uri = null ;
	
	@Autowired
	private ConfigInfoManager configInfoManager;
	
	public WSClientSenderApp() {
	}
    
	public void init() throws Exception {
		sslClient.setURI(uri);
		
	}
    
	public void send(long userid, String grid_code, String action) {
		this.grid_code = grid_code ;
		this.userid = userid ;
		this.action = action ;
		
		send();
	}
	
	 public void wsHeat() {
    	try {
    		this.sslClient.send("AppHeartBeat");
    	}catch(Exception e) {
    		logger.error("发送心跳信号异常;进行重连", e);
    		this.sslClient.reset(uri);
    	}
    }
	
	
	
	public void send(){
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("action", this.action);
			map.put("userid", userid+"");
			map.put("bookgrid_code", grid_code);
			String msg = JSONObject.toJSONString(map);
			logger.info("通知App信息： {}", msg);
			logger.info("this.sslClient: {}", this.sslClient);
			this.sslClient.send(msg);
		} catch (Exception e) {
			logger.info(e.getMessage(), e);
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.location = configInfoManager.getValue("SEND_APP_LOCATION") + "&token=" + WsStrUtils.getServerToken(serverName) + "&server=" + serverName;
		try {
			uri = new URI(location);
			logger.info("uri: {}", uri.toString());
		} catch (URISyntaxException e) {
			logger.error(e.getMessage());
		}
		
	}
}
